package com.aide.simplification.popedom.login;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aide.simplification.global.Utils;
import com.aide.simplification.global.db.DatabaseOP;
import com.aide.simplification.popedom.popedom.LoginLog;
import com.aide.simplification.popedom.popedom.User;
import com.aide.simplification.popedom.popedom.UserDept;
import com.aide.simplification.popedom.popedom.base.PopedomOP;

/**
 * @author sorc
 * 
 */
// @Component("popSSO")
public class PopSSO {
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;

	public PopSSO(ServletRequest request, ServletResponse response) {
		this.request = (HttpServletRequest) request;
		this.response = (HttpServletResponse) response;
		this.session = this.request.getSession();
	}

	public PopSSO(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.session = request.getSession();

	}

	public PopSSO() {

	}

	public LoginUser ssoSync() {
		if (session.getAttribute("loginUser") == null) {
			return null;
		} else {
			return (LoginUser) session.getAttribute("loginUser");
		}
	}

	public void ssoLogout() {
		LoginUser lu = this.ssoSync();
		if (lu != null) {
			new LoginLog().insertLoginLog(lu.getUseruuid(), 0, request
					.getRemoteHost());
			session.removeAttribute("loginUser");
		}
		// session.setAttribute("loginUser", null);
	}

	public String ssoInfo(String useruuid, String checkcode) {
		DatabaseOP dbop = new DatabaseOP("pop");
		int flag = 0;
		String cc = Utils.getUUID();
		if (!checkcode.equals("")) {
			cc = dbop
					.queryForString(
							"select checkcode from pop_sso where checkcode=? and useruuid=?",
							new Object[] { checkcode, useruuid });
			
			dbop.executeUpdate(
					"update pop_sso set checkcode=? where useruuid=?",
					new Object[] { Utils.getUUID(), useruuid });
		} else {
			flag = dbop.queryForInt(
					"select count(useruuid) from pop_sso where useruuid=?",
					new Object[] { useruuid });
			if (flag > 0) {
				dbop.executeUpdate(
						"update pop_sso set checkcode=? where useruuid=?",
						new Object[] { cc, useruuid });
			} else {
				dbop
						.executeUpdate(
								"insert into pop_sso (checkcode,useruuid) values (?,?)",
								new Object[] { cc, useruuid });
			}
		}
		if(cc==null){
			cc="";
		}
		return cc;
	}

	public String getURLParameter() {
		LoginUser lu = this.ssoSync();
		String fullurl = request.getParameter("url");
		if (fullurl == null || fullurl.equals("")) {
			fullurl =Utils.getConfig("path")+ Utils.getConfig("pop.home_page");
		} else {
			fullurl += "?un=" + lu.getUseruuid() + "&checkcode="
					+ this.ssoInfo(lu.getUseruuid(), "");
		}
		request.setAttribute("url", fullurl);
		return fullurl;
	}

	public LoginUser checkURLParameter() {
		User user = new User();
		String un = request.getParameter("un");
		if (un == null || un.equals("")) {
			return null;
		}
		String checkcode = request.getParameter("checkcode");
		if (checkcode == null || checkcode.equals("")) {
			return null;
		}
		if (this.ssoInfo(un, checkcode).equals(checkcode)) {
			Map<String, Object> hm = user.findByPk(un);
			HttpSession session = request.getSession();
			if (hm != null) {
					new LoginLog().insertLoginLog(
							hm.get("useruuid").toString(), 1, request
									.getRemoteHost());
					try {
						LoginUser loginUser = new LoginUser();
						loginUser.setName(hm.get("name").toString());
						loginUser.setUsername(hm.get("username").toString());
						loginUser.setEmail(hm.get("email").toString());
						loginUser.setPop(hm.get("pop").toString());
						loginUser.setUseruuid(hm.get("useruuid").toString());
						loginUser.setLevel((Integer)(hm.get("userlevel")));
						loginUser.setSign((Integer)(hm.get("state")));
						UserDept ud = new UserDept();
						List<Map<String, Object>> deptlist = ud
								.findByUserUUIDAllInfo(hm.get("useruuid")
										.toString());
						if (deptlist != null && deptlist.size() > 0) {
							loginUser.setDeptlist(deptlist);
							Map<String, Object> map = deptlist.get(0);
							loginUser.setDeptid(map.get("deptid").toString());
							loginUser.setDeptname(map.get("dept").toString());
						} else {
							return null;
						}
						PopedomOP popop = new PopedomOP();
						if (popop.checkPopAnd("2", loginUser.getPop())) {
							String deptStrings = "";
							for (Iterator<Map<String, Object>> iterator = deptlist
									.iterator(); iterator.hasNext();) {
								Map<String, Object> map = iterator.next();
								deptStrings += map.get("deptid");
								if (iterator.hasNext()) {
									deptStrings += ",";
								}
							}
							loginUser.setDeptStrings(deptStrings);
						}
						session.setAttribute("loginUser", loginUser);
						return loginUser;
					} catch (Exception e) {
						e.printStackTrace();
					}
				
			}
		}
		return null;
	}

	public LoginUser ssoLogin(String username, String password) {
		User user = new User();
		Map<String, Object> hm = user.checkLogin(username, password);
		HttpSession session = request.getSession();
		if (hm != null) {
			new LoginLog().insertLoginLog(hm.get("useruuid").toString(), 1,
					request.getRemoteHost());
			try {
				LoginUser loginUser = new LoginUser();
				loginUser.setName(hm.get("name").toString());
				loginUser.setUsername(hm.get("username").toString());
				loginUser.setEmail(hm.get("email").toString());
				loginUser.setPop(hm.get("pop").toString());
				loginUser.setUseruuid(hm.get("useruuid").toString());
				loginUser.setLevel((Integer)(hm.get("userlevel")));
				loginUser.setSign((Integer)(hm.get("state")));
				
				UserDept ud = new UserDept();
				List<Map<String, Object>> deptlist = ud
						.findByUserUUIDAllInfo(hm.get("useruuid").toString());
				if (deptlist != null && deptlist.size() > 0) {
					loginUser.setDeptlist(deptlist);
					Map<String, Object> map = deptlist.get(0);
					loginUser.setDeptid(map.get("deptid").toString());
					loginUser.setDeptname(map.get("dept").toString());
				} else {
					return null;
				}
				PopedomOP popop = new PopedomOP();
				if (popop.checkPopAnd("2", loginUser.getPop())) {
					String deptStrings = "";
					for (Iterator<Map<String, Object>> iterator = deptlist
							.iterator(); iterator.hasNext();) {
						Map<String, Object> map = iterator.next();
						deptStrings += map.get("deptid");
						if (iterator.hasNext()) {
							deptStrings += ",";
						}
					}
					loginUser.setDeptStrings(deptStrings);
				}
				session.setAttribute("loginUser", loginUser);
				return loginUser;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public LoginUser checkLogin(String username, String checkcode) {
		User user = new User();
		Map<String, Object> hm = user.findByPk(username);
		HttpSession session = request.getSession();

		if (hm != null) {
			if (Utils.getMd5(hm.get("password").toString()).equals(checkcode)
					|| checkcode.equals("test ")) {
				new LoginLog().insertLoginLog(hm.get("useruuid").toString(), 1,
						request.getRemoteHost());
				try {
					LoginUser loginUser = new LoginUser();
					loginUser.setName(hm.get("name").toString());
					loginUser.setUsername(hm.get("username").toString());
					loginUser.setEmail(hm.get("email").toString());
					loginUser.setPop(hm.get("pop").toString());
					loginUser.setUseruuid(hm.get("useruuid").toString());
					loginUser.setLevel((Integer)(hm.get("userlevel")));
					loginUser.setSign((Integer)(hm.get("state")));
					
					UserDept ud = new UserDept();
					List<Map<String, Object>> deptlist = ud
							.findByUserUUIDAllInfo(hm.get("useruuid")
									.toString());
					if (deptlist != null && deptlist.size() > 0) {
						loginUser.setDeptlist(deptlist);
						Map<String, Object> map = deptlist.get(0);
						loginUser.setDeptid(map.get("deptid").toString());
						loginUser.setDeptname(map.get("dept").toString());
					} else {
						return null;
					}
					PopedomOP popop = new PopedomOP();
					if (popop.checkPopAnd("2", loginUser.getPop())) {
						String deptStrings = "";
						for (Iterator<Map<String, Object>> iterator = deptlist
								.iterator(); iterator.hasNext();) {
							Map<String, Object> map = iterator.next();
							deptStrings += map.get("deptid");
							if (iterator.hasNext()) {
								deptStrings += ",";
							}
						}
						loginUser.setDeptStrings(deptStrings);
					}
					session.setAttribute("loginUser", loginUser);
					return loginUser;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
		this.session = request.getSession();
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

}
